package com.nuanshui.heatedloan.extension.pageable;

import org.springframework.core.MethodParameter;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableHandlerMethodArgumentResolver;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.method.support.ModelAndViewContainer;

import com.nuanshui.heatedloan.constant.GlobalParam;
import com.nuanshui.heatedloan.baseservice.model.UserAgent;
import com.nuanshui.heatedloan.pageable.Pager;

public class CustomPageableHandlerMethodArgumentResolver extends PageableHandlerMethodArgumentResolver {

	@Override
	public Pager resolveArgument(MethodParameter methodParameter,
			ModelAndViewContainer mavContainer, NativeWebRequest webRequest,
			WebDataBinderFactory binderFactory) {
		
	    UserAgent userAgent = 	(UserAgent) webRequest.getAttribute(GlobalParam.USER_AGENT, RequestAttributes.SCOPE_REQUEST);
		
	    Pageable pageable =  super.resolveArgument(methodParameter, mavContainer, webRequest,
				binderFactory);
		Pager pager = null;
		String channel = webRequest.getHeader("channel");
        if(userAgent!=null &&userAgent.getClient()!=null &&  (userAgent.getClient().startsWith("iPhone")) || "android".equals(userAgent.getClient())){
        	 pager =  getPager(pageable);
		} else if (channel != null && "weixin".equals(channel)){
			 pager =  getPager(pageable);
		} else {
			pager = new Pager(pageable.getPageNumber(),pageable.getPageSize());
		}
		return pager;
	}

	private Pager getPager(Pageable pageable){
		return new Pager(pageable.getPageNumber()+1,pageable.getPageSize());
	}
	
	@Override
	public boolean supportsParameter(MethodParameter parameter) {
		return Pageable.class.isAssignableFrom(parameter.getParameterType());
	}
}
